package com.benz.updatepack;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;

public class ActionHandler {
	
	public static void exec(String packDate, String packPath, String packSrcPath, String packFilePaths){
		File packPathDir = new File(packPath);
		if(!packPathDir.exists()){
			packPathDir.mkdirs();
		}
		String[] packFilePathsArray = packFilePaths.split(",");
		List<String> packFilePathsList = new ArrayList<String>();
		for(String packFilePath : packFilePathsArray){
			if(packFilePath.contains("\n")){
				packFilePath = packFilePath.substring(2);
			}
			if(new File(packSrcPath+ File.separator+packFilePath).exists()){
				packFilePathsList.add(packSrcPath+ File.separator+packFilePath);	
			}
			
			if(packFilePath.endsWith(".class")){
				//如果是类文件的话要将$1,$2的文件也插入
				File file = new File(packSrcPath+ File.separator+packFilePath);
				packFilePath = packFilePath.substring(packFilePath.lastIndexOf("/")+1, packFilePath.length());
				String parentPath = file.getParent();
				File parentFile = new File(parentPath);
				String[] filePaths = parentFile.list();
				for(String filePath : filePaths){
					if(filePath.contains(packFilePath.replace(".class", ""))){
						if(new File(parentPath+ File.separator+filePath).exists() && filePath.endsWith("class")){
							packFilePathsList.add(parentPath+ File.separator+filePath);	
						}
					}
				}
			}
		}
		
		for(String packFilePath : packFilePathsList){
			try {
				File packFile = new File(packFilePath);
				FileUtils.copyFileToDirectory(packFile, packPathDir);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
}
